var createError = require('http-errors');
var express = require('express');
var basicAuth = require('express-basic-auth');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');

var app = express();

// HTTP服务器身份
var authMiddleware = (basicAuth({
  users: {
    'admin': '123456',
    'user': 'user123456',
  },
  challenge: true, // 自动返回 401 质询响应
  realm: 'My Application Secure Area', // 领域名称，显示在浏览器弹窗上
  unauthorizedResponse: (req) => '无效的凭据。' // 自定义失败响应
}));

// 仅保护 /serverAuthentication 路由
app.get('/serverAuthentication', authMiddleware, (req, res) => {
  // 中间件会将认证成功的用户名放入 req.auth.user
  res.send(`你好，${req.auth.user}！访问成功。`);
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/images',express.static('images'));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.error(err);

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

